package com.example.receiptmanage.service;

import com.example.receiptmanage.dto.UpdateUserDTO;
import com.example.receiptmanage.dto.UserDTO;
import com.example.receiptmanage.entity.User;
import com.example.receiptmanage.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    // 根据用户名查找用户
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }
    // 创建新用户并编码密码
    public User createUser(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setRegisterDate(LocalDate.now());
        return userRepository.save(user);
    }

    // 将 User 实体转换为 UserDTO
    public UserDTO convertToDTO(User user) {
        UserDTO dto = new UserDTO();
        dto.setUserId(user.getUserId());
        dto.setUsername(user.getUsername());
        dto.setRegisterDate(user.getRegisterDate());
        return dto;
    }

    // 更新用户信息（不编码密码）
    public User updateUser(String username, UpdateUserDTO updateUserDTO) {
        Optional<User> optionalUser = userRepository.findByUsername(username);
        if (optionalUser.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }
        User user = optionalUser.get();
        if (updateUserDTO.getPassword() != null) {
            user.setPassword(passwordEncoder.encode(updateUserDTO.getPassword()));
        }
        // 只保存不编码密码
        return userRepository.save(user);
    }
}
